package org.example.code.test2024.nine_mouth;

import java.util.Stack;

public class test0910 {

    public boolean isValid(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }
        Stack<Character> stack = new Stack<>();
        char[] array = s.toCharArray();
        for (char c : array) {
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else if (c == ')' || c == ']' || c == '}') {
                if (stack.isEmpty()) {
                    return false;
                }
                char top = stack.pop();
                if (c == ')' && top != '(')
                    return false;
                if (c == ']' && top != '[')
                    return false;
                if (c == '}' && top != '{')
                    return false;
            }
        }
        return stack.isEmpty();
    }

    public String decodeString(String s) {
        if(s == null || s.length() == 0)
            return "";
        Stack<Integer> stack = new Stack<>();
        Stack<String> strStack = new Stack<>();
        char[] array = s.toCharArray();
        for(int i=0; i<array.length; i++){
            if(Character.isDigit(array[i])){
                int num = array[i] - '0';
                while(i+1<array.length && Character.isDigit(array[i+1])){
                    num = num*10 + (array[++i] - '0');
                }
                stack.push(num);
            }else if(array[i] == '['){
                strStack.push("");
            }else if(array[i] == ']'){
                StringBuilder sb = new StringBuilder();
                int count = stack.pop();
                String str = strStack.pop();
                for(int j=0; j<count; j++){
                    sb.append(str);
                }
                strStack.push(sb.toString());
            }else{
                strStack.push(String.valueOf(array[i]));
            }
        }
        StringBuilder sb = new StringBuilder();
        while(!strStack.isEmpty()){
            sb.append(strStack.pop());
        }
        return sb.toString();
    }

}
